from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Q
from user import models
from utils.jwttool import meansjwt
import re
import random
from utils.smscode import sms
import json
from utils.redis import redistool
from user import ser
from django.core.files.storage import default_storage
import uuid
from utils.myauthorization import MyAuthorization


# Create your views here.

class LoginByPwd(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        if not account or not password:
            return Response({'code': 400, 'msg': '账号或密码不能为空'})
        info = models.User.objects.filter(Q(username=account) | Q(iphone=account) | Q(email=account)).first()
        if not info:
            return Response({'code': 400, 'msg': '账号不存在'})
        if info.password != password:
            return Response({'code': 400, 'msg': '密码错误'})
        token = meansjwt.gettoken({"id": info.id})
        return Response({'code': 200, 'msg': '登录成功', 'data': {"token": token, "userid": info.id}})


class SendCode(APIView):
    def get(self, request):
        phone = request.query_params.get("phone", "")
        result = re.match(r"^1[3-9]\d{9}$", phone)
        if not phone:
            return Response({"code": "400", "msg": "手机号不能为空"})
        if not result:
            return Response({"code": "400", "msg": "手机号格式不正确"})
        if redistool.get_code(phone):
            return Response({"code": "400", "msg": "验证码已发送，请稍后重试"})
        code = str(random.randint(1000, 9999))
        res = json.loads(sms.send(phone, code))
        # 3 返回
        if res["statusCode"] == "000000":
            redistool.set_code(phone, code)
            return Response({"msg": "发送成功", "code": 200})
        else:
            return Response({"msg": "发送失败", "code": 400})


class Login(APIView):
    def post(self, request):
        phone = request.data.get('phone', '')
        code = request.data.get('code', '')
        if not phone or not code:
            return Response({'code': 400, 'msg': '手机号或验证码不能为空'})
        result = re.match(r"^1[3-9]\d{9}$", phone)
        if not result:
            return Response({"code": "400", "msg": "手机号格式不正确"})
        rediscode = redistool.get_code(phone)
        if rediscode != code:
            return Response({"code": "400", "msg": "验证码不正确"})
        info = models.User.objects.filter(iphone=phone).first()
        if not info:
            info = models.User.objects.create(iphone=phone)
        token = meansjwt.gettoken({'id': info.id})
        return Response({"code": "200", "msg": "登录成功", "data": {"token": token, "userid": info.id}})


class Info(APIView):
    authentication_classes = [MyAuthorization, ]

    def get(self, request):
        id = request.query_params.get("userid", "")
        if not id:
            return Response({"code": "400", "msg": "用户id不能为空"})
        info = models.User.objects.filter(id=id).first()
        if not info:
            return Response({"code": "400", "msg": "用户不存在"})
        # 返回当前用户信息
        userser = ser.UserSer(info)
        return Response({"msg": "获取用户信息成功", "code": 200, "data": userser.data})


class Upload(APIView):
    def post(self, request):
        file = request.data.get('file')
        if not file:
            return Response({"code": "400", "msg": "文件不能为空"})
        if file.size > 1024 * 1024 * 2:
            return Response({"code": "400", "msg": "文件大小不能超过2MB"})
        alltype = ['png', 'jpg', 'jpeg', 'gif', 'bmp']
        name = file.name.split('.')[-1]
        if name not in alltype:
            return Response({"code": "400", "msg": "文件格式不正确"})
        rename = uuid.uuid4().hex + '.' + name
        fileobj = default_storage.save('user/' + rename, file)
        url = default_storage.url(fileobj)
        return Response({"msg": "ok", "url": url})


class Register(APIView):
    def post(self, request):
        username = request.data.get("username", "")
        password = request.data.get("password", "")
        email = request.data.get("email", "")
        iphone = request.data.get("phone", "")
        headimg = request.data.get("headimg", "")
        info = models.User.objects.filter(username=username).first()
        if info:
            return Response({"code": "400", "msg": "用户名已存在"})
        if email:
            result = re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', email)
            if not result:
                return Response({"code": "400", "msg": "邮箱格式不正确"})
        info = models.User.objects.filter(email=email).first()
        if info:
            return Response({"code": "400", "msg": "邮箱已存在"})
        if iphone:
            result = re.match(r"^1[3-9]\d{9}$", iphone)
            if not result:
                return Response({"code": "400", "msg": "手机号格式不正确"})
        info = models.User.objects.filter(iphone=iphone).first()
        if info:
            return Response({"code": "400", "msg": "手机已存在"})
        if not username and not email and not iphone:
            return Response({"code": "400", "msg": "用户名 邮箱 手机号 必须有一个不能为空"})
        if not password:
            return Response({"code": "400", "msg": "密码不能为空"})
        if len(password) < 6:
            return Response({"code": "400", "msg": "密码不能小于6位"})
        user = models.User.objects.create(username=username, email=email, iphone=iphone, password=password,
                                          headimg=headimg)
        if user:
            return Response({"code": "200", "msg": "注册成功"})
